export default class WebSocketConnection {
  constructor(url, source) {
    this.url = url;
    this.source = source;
    this.socket = null;
    this.onMessage = null;
    this.onOpen = null;
    this.onClose = null;
    this.onError = null;
  }

  connect() {
    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      console.log("WebSocket connected");
      if (this.onOpen) this.onOpen();
    };

    this.socket.onmessage = (event) => {
      if (this.onMessage) this.onMessage(event.data);
    };

    this.socket.onclose = () => {
      console.log("WebSocket closed");
      if (this.onClose) this.onClose();
    };

    this.socket.onerror = (error) => {
      console.error("WebSocket error:", error);
      if (this.onError) this.onError(error);
    };
  }

  send(data) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
       this.socket.send(data);
    } else {
      console.warn("WebSocket is not connected. Attempting to reconnect...");
      this.close();
      this.connect();
      setTimeout(() => {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
          this.socket.send(data);
        } else {
          console.error("Failed to send data after reconnection attempt");
        }
      }, 1000);
      console.error("WebSocket is not connected");
    }
  }

  close() {
    if (this.socket) {
      this.socket.close();
    }
  }
}
